import axios from 'axios';
import store from '../vuex/store';
import router from 'vue-router';

//請求攔截器
axios.interceptors.request.use(
    config => {
        store.commit('ISLOADING', { isLoading: true });
        if (store.state.token) {  // 每次发送请求之前判断是否存在token，如果存在，则统一在http请求的header都加上token，不用每次请求都手动添加了
            // config.headers.Authorization = store.state.token;
            return config;
        } else {
            return Promise.reject(new Error("請重新登錄！"));
        }
    },
    err => {
        return Promise.reject(err);
    });
// 相應攔截器
axios.interceptors.response.use(
    config => {
        store.commit('ISLOADING', { isLoading: false });
        return config;
    },
    err => {
        return Promise.reject(err);
    }
)


export const commonAPI = (url, params, callback) => {
    let defaultConfig = {
        method: 'GET',
        baseURL: '/api',
        url: url + params,
    }
    return axios(defaultConfig)
        .then(res => {
            if (callback) {
                callback(res);
            } else {
                return res;
            }
        })
        .catch(err => {
            console.log(err.message);
            return err;
        });
}

export const commonAPIOPEN = (url, params, callback) => {
    let defaultConfig = {
        method: 'GET',
        baseURL: 'https://www.apiopen.top',
        url: url + "?" + params,
    }
    return axios(defaultConfig)
        .then(res => {
            if (callback) {
                callback(res);
            } else {
                return res;
            }
        })
        .catch(err => {
            console.log(err.message);
            return err;
        });
}

export const commonAPIJSON = (url, callback) => {
    let defaultConfig = {
        method: 'GET',
        baseURL: 'http://localhost:8080/static/json',
        url: url
    }
    return axios(defaultConfig)
        .then(res => {
            if (callback) {
                callback(res);
            } else {
                return res;
            }
        })
        .catch(err => {
            console.log(err.message);
            return err;
        })
}